<template>
  <Layout>
    <div class="order-management">
      <div class="search-panel">
        <div class="panel-title">
          <span>订单管理</span>
          <el-button type="primary" size="small" style="margin-left: 20px" @click="handleInitOrderData">初始化订单数据</el-button>
          <el-button type="success" size="small" style="margin-left: 10px" @click="openCreateOrderDialog">手动创建订单</el-button>
        </div>
        <div class="search-form">
          <el-row :gutter="20">
            <el-col :span="5">
              <el-select v-model="searchForm.searchType" placeholder="订单编号" class="w-full">
                <el-option label="订单编号" value="orderNo" />
                <el-option label="商品名称" value="productName" />
                <el-option label="收货人" value="receiverName" />
                <el-option label="手机号码" value="receiverPhone" />
              </el-select>
            </el-col>
            <el-col :span="13">
              <el-input 
                v-model="searchForm.keyword" 
                :placeholder="searchForm.searchType === 'orderNo' ? '请输入完整订单编号' : '请输入关键词'"
              />
              <div v-if="searchForm.searchType === 'orderNo'" class="search-tip">
                注意：订单编号需要精确输入，不支持模糊查询
              </div>
            </el-col>
          </el-row>
          
          <div class="time-filter mt-4">
            <span class="filter-label">下单时间</span>
            <el-date-picker
              v-model="searchForm.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 300px;"
              class="mr-2"
            />
            <div class="time-buttons">
              <el-button size="default" plain @click="setTimeRange('today')">今</el-button>
              <el-button size="default" plain @click="setTimeRange('yesterday')">昨</el-button>
              <el-button size="default" plain @click="setTimeRange('last7days')">近7天</el-button>
              <el-button size="default" plain @click="setTimeRange('last30days')">近30天</el-button>
            </div>
          </div>
          
          <div class="status-filters mt-4">
            <div class="filter-item">
              <span class="filter-label">订单状态</span>
              <el-select v-model="searchForm.orderStatus" placeholder="全部" style="width: 200px;">
                <el-option label="全部" value="" />
                <el-option label="待付款" value="1" />
                <el-option label="待发货" value="2" />
                <el-option label="部分发货" value="3" />
                <el-option label="已发货" value="4" />
                <el-option label="已完成" value="5" />
                <el-option label="已关闭" value="6" />
                <el-option label="售后中" value="7" />
              </el-select>
            </div>
            
            <div class="filter-item">
              <span class="filter-label">售后状态</span>
              <el-select v-model="searchForm.afterSaleStatus" placeholder="全部" style="width: 200px;">
                <el-option label="全部" value="" />
                <el-option label="无售后" value="0" />
                <el-option label="售后中" value="1" />
                <el-option label="待商家处理" value="2" />
                <el-option label="售后关闭" value="3" />
                <el-option label="退款成功" value="4" />
              </el-select>
            </div>
            
            <div class="filter-item">
              <span class="filter-label">推广渠道</span>
              <el-select v-model="searchForm.promotionChannel" placeholder="全部" style="width: 200px;">
                <el-option label="全部" value="" />
                <el-option label="官网" value="官网" />
                <el-option label="抖音直播" value="抖音直播" />
                <el-option label="腾讯惠聚" value="腾讯惠聚" />
                <el-option label="小红书订单" value="小红书订单" />
                <el-option label="微信小店" value="微信小店" />
                <el-option label="支付宝商家小程序" value="支付宝商家小程序" />
              </el-select>
            </div>
          </div>
          
          <div class="search-actions mt-4">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
      </div>
      
      <div class="order-tabs mt-4">
        <el-tabs v-model="activeTab" type="card">
          <el-tab-pane label="全部" name="all" />
          <el-tab-pane label="待付款" name="pending" />
          <el-tab-pane label="待发货" name="toShip" />
          <el-tab-pane label="部分发货" name="partialShipped" />
          <el-tab-pane label="已发货" name="shipped" />
          <el-tab-pane label="已完成" name="completed" />
          <el-tab-pane label="已关闭" name="closed" />
          <el-tab-pane label="售后中" name="afterSale" />
        </el-tabs>
      </div>
      
      <div class="order-table mt-4">
        <!-- 表头行 -->
        <div class="table-header">
          <el-checkbox v-model="allSelected" @change="toggleSelectAll">全选</el-checkbox>
          <div class="header-item flex-grow">商品</div>
          <div class="header-item text-center" style="width: 120px;">单价/数量</div>
          <div class="header-item text-center" style="width: 120px;">售后状态</div>
          <div class="header-item text-center" style="width: 120px;">应收金额</div>
          <div class="header-item text-center" style="width: 120px;">订单状态</div>
          <div class="header-item text-center" style="width: 150px;">操作</div>
        </div>
        
        <!-- 订单列表 -->
        <div v-if="orderList.length > 0">
          <div class="order-item" v-for="order in orderList" :key="order.id">
            <!-- 订单信息行 -->
            <div class="order-info-row">
              <el-checkbox v-model="order.selected" @change="handleOrderSelection"></el-checkbox>
              <span class="order-info-text">订单号：{{ order.orderNo || order.id }}</span>
              <span class="order-info-text">下单时间：{{ order.orderTime }}</span>
              <span class="order-info-text">{{ order.liveStream }}</span>
              <span class="order-info-text">用户名：{{ order.customerName }}</span>
            </div>
            
            <!-- 商品信息行 -->
            <div class="order-content">
              <!-- 商品信息 -->
              <div class="product-column flex-grow">
                <div v-for="(item, index) in order.items" :key="index" class="product-item">
                  <div class="product-img">
                    <el-image :src="item.image || '/public/OIP-C.webp'" fit="cover" style="width: 80px; height: 80px;" />
                  </div>
                  <div class="product-info">
                    <div class="product-name">{{ item.name }}</div>
                    <div class="product-sku">规格ID：{{ item.skuId }}</div>
                  </div>
                </div>
                <div class="user-note" v-if="order.userNote">
                  <div class="user-remark"><el-icon><InfoFilled /></el-icon> 用户备注：{{ order.userNote }}</div>
                  <div v-if="order.orderNote" class="order-note-edit">
                    <el-icon><Edit /></el-icon> 订单备注：{{ order.orderNote }}
                  </div>
                </div>
              </div>
              
              <!-- 单价/数量 -->
              <div class="text-center" style="width: 120px;">
                <div v-for="(item, idx) in order.items" :key="'price-' + idx" class="price-quantity-item">
                  <div>{{ item.price }}</div>
                  <div>x {{ item.quantity }}</div>
                </div>
              </div>
              
              <!-- 售后状态 -->
              <div class="text-center" style="width: 120px;">
                <div>
                  <el-tag v-if="order.afterSaleStatus" :type="getAfterSaleStatusType(order.afterSaleStatus)" size="small" effect="light">
                    {{ getAfterSaleStatusText(order.afterSaleStatus) }}
                  </el-tag>
                  <span v-else>无售后</span>
                </div>
                <div class="ship-status mt-1">
                  <el-tag :type="getShipStatusType(order.shippedCount || 0, order.totalCount || 1)" size="small" effect="light">
                    {{ formatShipStatus(order.shippedCount || 0, order.totalCount || 1) }}
                  </el-tag>
                </div>
              </div>
              
              <!-- 应收金额 -->
              <div class="text-center" style="width: 120px;">
                <div>{{ order.receivableAmount }}</div>
                <el-link type="primary" size="small" v-if="order.orderStatus === 'pending' || order.orderStatus === '1'" class="price-edit" @click="handleChangePrice(order, '¥' + calculatePayAmount(order))">
                  改价
                </el-link>
              </div>
              
              <!-- 订单状态 -->
              <div class="text-center" style="width: 120px;">
                <el-tag :type="getOrderStatusType(order.orderStatus)" size="small" effect="light">
                  {{ formatOrderStatus(order.orderStatus) }}
                </el-tag>
                <div v-if="order.isOverdue" class="mt-1">
                  <el-tag type="danger" size="small" effect="light">发货已超时</el-tag>
                </div>
              </div>
              
              <!-- 操作 -->
              <div class="operation-column" style="width: 150px;">
                <el-link type="primary" class="operation-link" @click="viewOrderDetail(order)">订单详情</el-link>
                <el-link type="primary" class="operation-link" v-if="order.orderStatus === 'pending' || order.orderStatus === '1'" @click="openCancelDialog(order)">取消订单</el-link>
                <el-link type="primary" class="operation-link" v-if="order.orderStatus === 'paid' || order.orderStatus === '2'" @click="openShipDialog(order)">发货</el-link>
                <el-link type="primary" class="operation-link" @click="openAddressDialog(order)">修改地址</el-link>
                <el-link type="danger" class="operation-link" @click="handleDeleteOrder(order)">删除订单</el-link>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="empty-state">
          <el-empty 
            description="暫無訂單數據" 
            :image-size="200"
          >
            <template #description>
              <p>{{ loading ? '正在加載數據...' : isSearchActive() ? '沒有找到符合條件的訂單' : '暫無訂單數據' }}</p>
            </template>
            <el-button v-if="!loading && !isSearchActive()" type="primary" @click="handleInitOrderData">初始化訂單數據</el-button>
          </el-empty>
        </div>
        
        <!-- 批量操作区域 -->
        <div class="batch-operation">
          <el-checkbox v-model="allSelected" @change="toggleSelectAll">全选</el-checkbox>
          <span class="batch-operation-text">批量操作</span>
          <el-button class="batch-btn" plain>导出</el-button>
          <el-button class="batch-btn" plain>取消订单</el-button>
          <el-button class="batch-btn" plain>批量发货</el-button>
          <el-button class="batch-btn" plain>批量备注</el-button>
          <el-button class="batch-btn" plain>批量导出</el-button>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-container" v-if="total > 0">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-size="searchForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :current-page="searchForm.currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      
      <!-- 订单详情抽屉 -->
      <el-drawer
        v-model="drawer.visible"
        :title="'订单详情 - ' + (currentOrder?.orderNo || currentOrder?.id || '')"
        size="60%"
        :destroy-on-close="false"
      >
        <div v-if="currentOrder" class="order-detail-drawer">
          <div class="info-section">
            <div class="section-title">订单信息</div>
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">订单编号：</span>
                <span>{{ currentOrder.orderNo || currentOrder.id }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">下单时间：</span>
                <span>{{ currentOrder.orderTime }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">订单状态：</span>
                <span>{{ formatOrderStatus(currentOrder.orderStatus) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">推广渠道：</span>
                <span>{{ currentOrder.liveStream }}</span>
              </div>
            </div>
          </div>
          
          <div class="info-section">
            <div class="section-title">收货信息</div>
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">收货人：</span>
                <span>{{ currentOrder.receiverName }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">联系电话：</span>
                <span>{{ currentOrder.receiverPhone }}</span>
              </div>
              <div class="info-item full-width">
                <span class="info-label">收货地址：</span>
                <span>{{ currentOrder.receiverRegion }} {{ currentOrder.receiverAddress }}</span>
              </div>
            </div>
          </div>
          
          <div class="info-section">
            <div class="section-title">商品信息</div>
            <el-table :data="currentOrder.items" border style="width: 100%">
              <el-table-column label="商品图片" width="120" align="center">
                <template #default="{ row }">
                  <el-image :src="row.image || '/public/OIP-C.webp'" fit="cover" style="width: 60px; height: 60px;" />
                </template>
              </el-table-column>
              <el-table-column prop="name" label="商品名称" min-width="200" />
              <el-table-column label="规格" width="150">
                <template #default="{ row }">
                  <span>{{ row.specs || '默认规格' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="单价" prop="price" width="100" align="center" />
              <el-table-column label="数量" prop="quantity" width="80" align="center" />
              <el-table-column label="小计" width="120" align="center">
                <template #default="{ row }">
                  {{ calculateSubtotal(row) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <div class="info-section">
            <div class="section-title">金额信息</div>
            <div class="amount-info">
              <div class="amount-item">
                <span>商品总额：</span>
                <span>{{ currentOrder.receivableAmount }}</span>
              </div>
              <div class="amount-item">
                <span>运费：</span>
                <span>¥0.00</span>
              </div>
              <div class="amount-item">
                <span>优惠金额：</span>
                <span>¥0.00</span>
              </div>
              <div class="amount-item total">
                <span>实付金额：</span>
                <span class="total-amount">{{ currentOrder.receivableAmount }}</span>
              </div>
            </div>
          </div>
          
          <div class="info-section" v-if="currentOrder.userNote">
            <div class="section-title">备注信息</div>
            <div class="note-info">
              <div class="note-item">
                <span class="info-label">用户备注：</span>
                <span>{{ currentOrder.userNote }}</span>
              </div>
              <div class="note-item" v-if="currentOrder.orderNote">
                <span class="info-label">订单备注：</span>
                <span>{{ currentOrder.orderNote }}</span>
              </div>
            </div>
          </div>
          
          <div class="action-section" v-if="currentOrder && (currentOrder.orderStatus === 'pending' || currentOrder.orderStatus === '1')">
            <el-button type="primary" @click="openAddressDialog(currentOrder)">修改地址</el-button>
            <el-button type="danger" @click="openCancelDialog(currentOrder)">取消订单</el-button>
            <el-button>改价</el-button>
          </div>
          <div class="action-section" v-else-if="currentOrder && (currentOrder.orderStatus === 'paid' || currentOrder.orderStatus === '2')">
            <el-button type="primary" @click="openAddressDialog(currentOrder)">修改地址</el-button>
            <el-button type="success" @click="openShipDialog(currentOrder)">发货</el-button>
          </div>
        </div>
      </el-drawer>
      
      <!-- 取消订单弹窗 -->
      <el-dialog
        v-model="cancelDialog.visible"
        title="取消订单"
        width="500px"
        destroy-on-close
      >
        <el-form :model="cancelDialog.form" ref="cancelFormRef" :rules="cancelDialog.rules" label-width="100px">
          <el-form-item label="取消原因" prop="reasons">
            <el-select
              v-model="cancelDialog.form.reasons"
              multiple
              placeholder="请选择取消原因"
              style="width: 100%;"
            >
              <el-option label="商品缺货" value="stock" />
              <el-option label="价格错误" value="price" />
              <el-option label="客户主动取消" value="customer" />
              <el-option label="其他原因" value="other" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="cancelDialog.form.remark"
              type="textarea"
              placeholder="请输入备注（选填）"
              maxlength="100"
              show-word-limit
              rows="4"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancelDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="submitCancelOrder">确定</el-button>
          </div>
        </template>
      </el-dialog>
      
      <!-- 修改收货地址弹窗 -->
      <el-dialog
        v-model="addressDialog.visible"
        title="修改收货地址"
        width="500px"
        destroy-on-close
      >
        <el-form :model="addressDialog.form" ref="addressFormRef" :rules="addressDialog.rules" label-width="100px">
          <el-form-item label="收货人" prop="name">
            <el-input
              v-model="addressDialog.form.name"
              placeholder="请输入收货人姓名"
              maxlength="30"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input
              v-model="addressDialog.form.phone"
              placeholder="请输入收货人手机号"
              maxlength="11"
            ></el-input>
          </el-form-item>
          <el-form-item label="所在地区" prop="region">
            <el-cascader
              v-model="addressDialog.form.region"
              :options="addressDialog.regionOptions"
              placeholder="请选择省/市/区/街道"
              style="width: 100%;"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input
              v-model="addressDialog.form.address"
              type="textarea"
              placeholder="请输入详细地址"
              maxlength="30"
              show-word-limit
              rows="3"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="addressDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="submitAddressChange">确定</el-button>
          </div>
        </template>
      </el-dialog>
      
      <!-- 发货弹窗 -->
      <el-dialog
        v-model="shipDialog.visible"
        title="订单发货"
        width="500px"
        destroy-on-close
      >
        <el-form :model="shipDialog.form" ref="shipFormRef" :rules="shipDialog.rules" label-width="100px">
          <el-form-item label="物流公司" prop="expressCompany">
            <el-select v-model="shipDialog.form.expressCompany" placeholder="请选择物流公司" style="width: 100%;">
              <el-option label="顺丰速运" value="SF"></el-option>
              <el-option label="中通快递" value="ZTO"></el-option>
              <el-option label="圆通快递" value="YTO"></el-option>
              <el-option label="韵达快递" value="YD"></el-option>
              <el-option label="申通快递" value="STO"></el-option>
              <el-option label="京东物流" value="JD"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物流单号" prop="trackingNumber">
            <el-input
              v-model="shipDialog.form.trackingNumber"
              placeholder="请输入物流单号"
              maxlength="30"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="shipDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="submitShipOrder">确定</el-button>
          </div>
        </template>
      </el-dialog>
      
      <!-- 创建订单弹窗 -->
      <el-dialog
        v-model="createOrderDialog.visible"
        title="手动创建订单"
        width="700px"
        destroy-on-close
      >
        <el-form :model="createOrderDialog.form" ref="createOrderFormRef" :rules="createOrderDialog.rules" label-width="100px">
          <!-- 客户信息部分 -->
          <div class="dialog-section-title">客户信息</div>
          <el-form-item label="客户姓名" prop="customerName">
            <el-input v-model="createOrderDialog.form.customerName" placeholder="请输入客户姓名"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="createOrderDialog.form.phone" placeholder="请输入手机号码"></el-input>
          </el-form-item>
          
          <!-- 收货地址部分 -->
          <div class="dialog-section-title">收货地址</div>
          <el-form-item label="收货人" prop="receiverName">
            <el-input v-model="createOrderDialog.form.receiverName" placeholder="请输入收货人姓名"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="receiverPhone">
            <el-input v-model="createOrderDialog.form.receiverPhone" placeholder="请输入收货人电话"></el-input>
          </el-form-item>
          <el-form-item label="所在地区" prop="region">
            <el-cascader
              v-model="createOrderDialog.form.region"
              :options="addressDialog.regionOptions"
              placeholder="请选择省/市/区/街道"
              style="width: 100%;"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input
              v-model="createOrderDialog.form.address"
              type="textarea"
              placeholder="请输入详细地址"
              rows="2"
            ></el-input>
          </el-form-item>
          
          <!-- 商品信息部分 -->
          <div class="dialog-section-title">商品信息</div>
          <div v-for="(item, index) in createOrderDialog.form.items" :key="index" class="product-form-item">
            <div class="product-form-header">
              <span>商品 {{ index + 1 }}</span>
              <el-button 
                v-if="createOrderDialog.form.items.length > 1" 
                type="danger" 
                size="small" 
                icon="Delete" 
                circle 
                @click="removeProductItem(index)"
              ></el-button>
            </div>
            
            <el-form-item :label="'商品名称'" :prop="'items.' + index + '.productName'" :rules="{ required: true, message: '请输入商品名称', trigger: 'blur' }">
              <el-input v-model="item.productName" placeholder="请输入商品名称"></el-input>
            </el-form-item>
            
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item :label="'单价'" :prop="'items.' + index + '.price'" :rules="{ required: true, message: '请输入单价', trigger: 'blur' }">
                  <el-input-number v-model="item.price" :precision="2" :step="0.01" :min="0" controls-position="right"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="'数量'" :prop="'items.' + index + '.quantity'" :rules="{ required: true, message: '请输入数量', trigger: 'blur' }">
                  <el-input-number v-model="item.quantity" :min="1" :step="1" controls-position="right"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="'规格'" :prop="'items.' + index + '.specifications'">
                  <el-input v-model="item.specifications" placeholder="请输入规格"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item :label="'商品图片'" :prop="'items.' + index + '.productImg'">
              <el-input v-model="item.productImg" placeholder="请输入商品图片URL"></el-input>
            </el-form-item>
          </div>
          
          <div class="add-product-btn">
            <el-button type="primary" plain icon="Plus" @click="addProductItem">添加商品</el-button>
          </div>
          
          <!-- 订单信息部分 -->
          <div class="dialog-section-title">订单信息</div>
          <el-form-item label="订单备注" prop="remark">
            <el-input
              v-model="createOrderDialog.form.remark"
              type="textarea"
              placeholder="请输入订单备注（选填）"
              rows="2"
            ></el-input>
          </el-form-item>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="推广渠道" prop="channel">
                <el-select v-model="createOrderDialog.form.channel" placeholder="请选择推广渠道" style="width: 100%;">
                  <el-option label="官网" value="官网"></el-option>
                  <el-option label="抖音直播" value="抖音直播"></el-option>
                  <el-option label="腾讯惠聚" value="腾讯惠聚"></el-option>
                  <el-option label="小红书订单" value="小红书订单"></el-option>
                  <el-option label="微信小店" value="微信小店"></el-option>
                  <el-option label="支付宝商家小程序" value="支付宝商家小程序"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单状态" prop="status">
                <el-select v-model="createOrderDialog.form.status" placeholder="请选择订单状态" style="width: 100%;">
                  <el-option label="待付款" :value="OrderStatus.Pending"></el-option>
                  <el-option label="待发货" :value="OrderStatus.Paid"></el-option>
                  <el-option label="已发货" :value="OrderStatus.Shipped"></el-option>
                  <el-option label="已完成" :value="OrderStatus.Completed"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="createOrderDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="submitCreateOrder">创建订单</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Edit, InfoFilled } from '@element-plus/icons-vue';
import Layout from '@/components/Layout.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import request from '@/utils/request';
import { API } from '@/utils/config';
import { 
  getOrderList, 
  OrderStatus, 
  AfterSaleStatus, 
  type Order, 
  type OrderListParams,
  cancelOrder,
  updateOrderStatus,
  changeOrderPrice,
  updateOrderAddress,
  deleteOrder,
  shipOrder,
  batchCreateOrders,
  initOrderData
} from '@/api/order';

const router = useRouter();

const activeTab = ref('all');
const allSelected = ref(false);

// 搜索表单
const searchForm = reactive({
  searchType: 'orderNo', // 搜索类型：订单编号、商品名称、收货人、手机号码
  keyword: '', // 关键词
  timeRange: [] as string[], // 下单时间范围
  orderStatus: '', // 订单状态
  afterSaleStatus: '', // 售后状态
  promotionChannel: '', // 推广渠道
  currentPage: 1,
  pageSize: 10
});

// 设置时间范围的快捷按钮
const setTimeRange = (type: string) => {
  const today = dayjs();
  
  switch (type) {
    case 'today': // 今天
      searchForm.timeRange = [
        today.format('YYYY-MM-DD'),
        today.format('YYYY-MM-DD')
      ];
      break;
    case 'yesterday': // 昨天
      const yesterday = today.subtract(1, 'day');
      searchForm.timeRange = [
        yesterday.format('YYYY-MM-DD'),
        yesterday.format('YYYY-MM-DD')
      ];
      break;
    case 'last7days': // 近7天
      searchForm.timeRange = [
        today.subtract(6, 'day').format('YYYY-MM-DD'),
        today.format('YYYY-MM-DD')
      ];
      break;
    case 'last30days': // 近30天
      searchForm.timeRange = [
        today.subtract(29, 'day').format('YYYY-MM-DD'),
        today.format('YYYY-MM-DD')
      ];
      break;
    default:
      searchForm.timeRange = [];
      break;
  }
};

// 处理搜索
const handleSearch = () => {
  // 重置页码
  searchForm.currentPage = 1;
  // 获取订单列表数据
  fetchOrderList();
};

// 重置搜索条件
const handleReset = () => {
  searchForm.searchType = 'orderNo';
  searchForm.keyword = '';
  searchForm.timeRange = [];
  searchForm.orderStatus = '';
  searchForm.afterSaleStatus = '';
  searchForm.promotionChannel = '';
  searchForm.currentPage = 1;
  // 重置后可以选择是否自动搜索
  fetchOrderList();
};

// 获取订单列表数据
const fetchOrderList = async () => {
  try {
    loading.value = true;
    
    // 构建查询参数
    const params: OrderListParams = {
      page: searchForm.currentPage,
      pageSize: searchForm.pageSize,
    };
    
    // 添加搜索条件
    if (searchForm.keyword) {
      params.searchType = searchForm.searchType;
      params.keyword = searchForm.keyword;
    }
    
    // 添加时间范围
    if (searchForm.timeRange && searchForm.timeRange.length === 2) {
      params.startDate = searchForm.timeRange[0];
      params.endDate = searchForm.timeRange[1];
    }
    
    // 添加状态过滤
    if (searchForm.orderStatus) {
      params.status = searchForm.orderStatus;
    }
    
    if (searchForm.afterSaleStatus) {
      params.refundStatus = searchForm.afterSaleStatus;
    }
    
    if (searchForm.promotionChannel) {
      params.channel = searchForm.promotionChannel;
    }
    
    // 根据标签页自动筛选订单状态
    if (activeTab.value !== 'all') {
      const tabStatusMap: Record<string, string> = {
        'pending': OrderStatus.Pending,
        'toShip': OrderStatus.Paid,
        'partialShipped': OrderStatus.Partial,
        'shipped': OrderStatus.Shipped,
        'completed': OrderStatus.Completed,
        'closed': OrderStatus.Closed,
        'afterSale': '1' // 售後中狀態對應 refundStatus 為 1
      };
      
      if (tabStatusMap[activeTab.value]) {
        if (activeTab.value === 'afterSale') {
          params.refundStatus = tabStatusMap[activeTab.value];
        } else {
          params.status = tabStatusMap[activeTab.value];
        }
      }
    }
    
    try {
      // 先尝试从LeanCloud获取数据
      const res: any = await getOrderList(params);
      
      // 处理返回的数据
      if (res && res.results && res.results.length > 0) {
        const formattedOrders = res.results.map((order: any) => {
          // 處理商品項目
          let orderItems = [];
          if (order.items && Array.isArray(order.items)) {
            orderItems = order.items.map((item: any) => {
              return {
                image: item.productImg || '/public/OIP-C.webp',
                name: item.productName || '商品名称',
                skuId: item.skuId || '000000',
                price: typeof item.price === 'number' ? `¥${item.price}` : item.price || '¥0',
                quantity: item.quantity || 1,
                specs: item.specifications || '默认规格',
                discount: item.discount || 0,
                shipping: item.shipping || 0
              };
            });
          } else {
            // 如果沒有商品項目，創建一個默認項目
            orderItems = [{
              image: '/public/OIP-C.webp',
              name: order.productName || '福满园农家生态香米',
              skuId: order.skuId || '2468896545',
              price: `¥${order.price || 56.90}`,
              quantity: order.quantity || 1,
              specs: '默认规格',
              discount: order.discount || 0,
              shipping: order.shipping || 0
            }];
          }

          return {
            id: order.objectId,
            orderNo: order.orderNo || `P${dayjs(order.createdAt).format('YYYYMMDD')}${Math.floor(10000 + Math.random() * 90000)}`,
            orderTime: order.createdAt ? dayjs(order.createdAt).format('YYYY-MM-DD HH:mm:ss') : '',
            liveStream: order.channel || '官网',
            customerName: order.receiverName || '未知用户',
            orderStatus: order.status?.toString() || '1',
            afterSaleStatus: order.refundStatus?.toString() || '0',
            receivableAmount: typeof order.payAmount === 'number' ? `¥${order.payAmount}` : order.payAmount || '¥0',
            selected: false,
            shippedCount: order.shippedCount || 0,
            totalCount: order.totalCount || 1,
            isOverdue: checkOrderOverdue(order.status?.toString(), order.createdAt),
            items: orderItems,
            userNote: order.remark || '',
            orderNote: order.sellerRemark || '',
            receiverName: order.receiverName || '',
            receiverPhone: order.receiverPhone || '',
            receiverAddress: order.receiverAddress || '',
            receiverRegion: order.receiverRegion || ''
          };
        });
        
        orderList.value = formattedOrders;
        total.value = res.count || formattedOrders.length;
      } else {
        // 如果没有数据，显示空列表
        orderList.value = [];
        total.value = 0;
        // 如果是搜索結果為空，顯示提示
        if (isSearchActive()) {
          ElMessage.info('沒有找到符合條件的訂單');
        }
      }
    } catch (error: any) {
      console.error('获取订单列表失败', error);
      // 发生错误时，显示空列表
      orderList.value = [];
      total.value = 0;
      // 顯示友好的錯誤提示，而不是技術錯誤詳情
      ElMessage.error('獲取訂單數據失敗，請稍後重試');
    } finally {
      loading.value = false;
    }
  } catch (error: any) {
    console.error('构建查询参数失败', error);
    orderList.value = [];
    total.value = 0;
    loading.value = false;
    ElMessage.error('查詢參數錯誤，請檢查輸入並重試');
  }
};

// 上传模拟订单数据到LeanCloud
const uploadMockOrdersToLeanCloud = async () => {
  try {
    loading.value = true;
    // 使用模拟数据
    await batchCreateOrders(orderList.value);
    ElMessage.success('订单数据初始化成功');
    
    // 重新获取数据
    const params: OrderListParams = {
      page: searchForm.currentPage,
      pageSize: searchForm.pageSize,
    };
    const res: any = await getOrderList(params);
    
    if (res && res.results) {
      const formattedOrders = res.results.map((order: any) => {
        // 處理商品項目
        let orderItems = [];
        if (order.items && Array.isArray(order.items)) {
          orderItems = order.items.map((item: any) => {
            return {
              image: item.productImg || '/public/OIP-C.webp',
              name: item.productName || '商品名称',
              skuId: item.skuId || '000000',
              price: `¥${item.price || 0}`,
              quantity: item.quantity || 1,
              specs: item.specifications || '默认规格',
              discount: item.discount || 0,
              shipping: item.shipping || 0
            };
          });
        } else {
          // 如果沒有商品項目，創建一個默認項目
          orderItems = [{
            image: '/public/OIP-C.webp',
            name: order.productName || '福满园农家生态香米',
            skuId: order.skuId || '2468896545',
            price: `¥${order.price || 56.90}`,
            quantity: order.quantity || 1,
            specs: '默认规格',
            discount: order.discount || 0,
            shipping: order.shipping || 0
          }];
        }

        return {
          id: order.objectId,
          orderNo: order.orderNo || `P${dayjs(order.createdAt).format('YYYYMMDD')}${Math.floor(10000 + Math.random() * 90000)}`,
          orderTime: order.createdAt ? dayjs(order.createdAt).format('YYYY-MM-DD HH:mm:ss') : '',
          liveStream: order.channel || '官网',
          customerName: order.receiverName || '未知用户',
          orderStatus: order.status?.toString() || '1',
          afterSaleStatus: order.refundStatus?.toString() || '0',
          receivableAmount: `¥${order.payAmount || 0}`,
          selected: false,
          shippedCount: order.shippedCount || 0,
          totalCount: order.totalCount || 1,
          isOverdue: checkOrderOverdue(order.status?.toString(), order.createdAt),
          items: orderItems,
          userNote: order.remark || '',
          orderNote: order.sellerRemark || '',
          receiverName: order.receiverName || '',
          receiverPhone: order.receiverPhone || '',
          receiverAddress: order.receiverAddress || '',
          receiverRegion: order.receiverRegion || ''
        };
      });
      
      orderList.value = formattedOrders;
      total.value = res.count || formattedOrders.length;
    }
    
    loading.value = false;
  } catch (error) {
    loading.value = false;
    console.error('上传模拟订单数据失败', error);
    ElMessage.error('订单数据初始化失败');
  }
};

// 检查是否有搜索条件激活
const isSearchActive = () => {
  return searchForm.keyword || 
    (searchForm.timeRange && searchForm.timeRange.length === 2) || 
    searchForm.orderStatus || 
    searchForm.afterSaleStatus || 
    searchForm.promotionChannel || 
    activeTab.value !== 'all';
};

// 格式化订单状态
const formatOrderStatus = (status: string | number) => {
  const statusMap: Record<string, string> = {
    '1': '待付款',
    '2': '待发货',
    '3': '部分发货',
    '4': '待收货',
    '5': '交易完成',
    '6': '交易关闭',
    'pending': '待付款',
    'paid': '待发货',
    'partial': '部分发货',
    'shipped': '待收货',
    'completed': '交易完成',
    'closed': '交易关闭'
  };
  
  return statusMap[status + ''] || '未知状态';
};

// 获取订单状态对应的样式类型
const getOrderStatusType = (status: string | number) => {
  const typeMap: Record<string, 'primary' | 'success' | 'info' | 'warning' | 'danger'> = {
    '1': 'warning',   // 待付款
    '2': 'info',      // 待发货
    '3': 'info',      // 部分发货
    '4': 'primary',   // 待收货
    '5': 'success',   // 交易完成
    '6': 'danger',    // 交易关闭
    'pending': 'warning',
    'paid': 'info',
    'partial': 'info',
    'shipped': 'primary',
    'completed': 'success',
    'closed': 'danger'
  };
  
  return typeMap[status + ''] || 'info';
};

// 获取售后状态文本
const getAfterSaleStatusText = (status: string | number) => {
  const statusMap: Record<string, string> = {
    '0': '无售后',
    '1': '售后中',
    '2': '待商家处理',
    '3': '售后关闭',
    '4': '退款成功',
    '无售后': '无售后'
  };
  
  return statusMap[status + ''] || '未知状态';
};

// 获取售后状态样式类型
const getAfterSaleStatusType = (status: string | number) => {
  const typeMap: Record<string, '' | 'primary' | 'success' | 'info' | 'warning' | 'danger'> = {
    '0': '',           // 无售后
    '1': 'warning',    // 售后中
    '2': 'danger',     // 待商家处理
    '3': 'info',       // 售后关闭
    '4': 'success',    // 退款成功
    '无售后': ''
  };
  
  return typeMap[status + ''] || 'info';
};

// 格式化发货状态
const formatShipStatus = (shipped: number, total: number) => {
  if (shipped === 0) return '未发货';
  if (shipped === total) return '已发货';
  return `${shipped}/${total}已发货`;
};

// 获取发货状态样式类型
const getShipStatusType = (shipped: number, total: number): 'primary' | 'success' | 'info' | 'warning' | 'danger' => {
  if (shipped === 0) return 'info';
  if (shipped === total) return 'success';
  return 'warning';
};

// 计算实际应收金额
const calculatePayAmount = (item: any) => {
  // 单价 * 数量 - 优惠金额 + 运费
  const price = parseFloat(item.price.replace('¥', ''));
  const quantity = item.quantity || 1;
  const discount = item.discount || 0;
  const shipping = item.shipping || 0;
  
  return '¥' + (price * quantity - discount + shipping).toFixed(2);
};

// 计算商品小计
const calculateSubtotal = (item: any) => {
  const price = parseFloat(item.price.replace('¥', ''));
  return '¥' + (price * item.quantity).toFixed(2);
};

// 加载状态
const loading = ref(false);

// 模拟订单数据
const orderList = ref<any[]>([
  {
    id: 'P2035091978689',
    orderTime: '2035-09-19 9:39:39',
    liveStream: '抖音直播',
    customerName: '周杰伦',
    orderStatus: 'closed',
    afterSaleStatus: '无售后',
    receivableAmount: '¥56.90',
    selected: false,
    shippedCount: 0,
    totalCount: 1,
    isOverdue: false,
    items: [
      {
        image: '',
        name: '飘柔洗护香波',
        skuId: '2468896545',
        price: '¥56.90',
        quantity: 1,
        specs: '默认规格',
        discount: 0,
        shipping: 0
      }
    ],
    priceAndQuantity: '¥56.90 x 1',
    userNote: '',
    orderNote: '',
    receiverName: '周杰伦',
    receiverPhone: '13800138000',
    receiverAddress: '天朝北路1号楼',
    receiverRegion: '北京市/北京市/朝阳区/建外街道'
  },
  {
    id: 'P2035091978690',
    orderTime: '2035-09-18 15:25:30',
    liveStream: '官网',
    customerName: '林俊杰',
    orderStatus: 'paid',
    afterSaleStatus: '无售后',
    receivableAmount: '¥128.50',
    selected: false,
    shippedCount: 0,
    totalCount: 1,
    isOverdue: true,
    items: [
      {
        image: '',
        name: '有机蔬菜礼盒',
        skuId: '2468896546',
        price: '¥128.50',
        quantity: 1,
        specs: '精品装',
        discount: 10,
        shipping: 8
      }
    ],
    priceAndQuantity: '¥128.50 x 1',
    userNote: '请确保新鲜',
    orderNote: '',
    receiverName: '林俊杰',
    receiverPhone: '13900139000',
    receiverAddress: '演唱会路2号',
    receiverRegion: '上海市/上海市/徐汇区/湖南路街道'
  },
  {
    id: 'P2035091978689',
    orderTime: '2035-09-19 9:39:39',
    liveStream: '微信小店',
    customerName: '周杰伦',
    orderStatus: 'partial',
    afterSaleStatus: '无售后',
    receivableAmount: '¥199.80',
    selected: false,
    shippedCount: 1,
    totalCount: 2,
    isOverdue: false,
    items: [
      {
        image: '',
        name: '格兰仕烤箱12L 自动',
        skuId: '2468896545',
        price: '¥69.90',
        quantity: 2,
        specs: '默认规格',
        discount: 0,
        shipping: 0
      },
      {
        image: '',
        name: '索迪斯手持除螨仪',
        skuId: '2468896617',
        price: '¥129.90',
        quantity: 1,
        specs: '默认规格',
        discount: 0,
        shipping: 0
      }
    ],
    priceAndQuantity: '¥69.90 x 2 + ¥129.90 x 1',
    userNote: '用户需要锅碗炉盘',
    orderNote: '',
    receiverName: '周杰伦',
    receiverPhone: '13800138000',
    receiverAddress: '天朝北路1号楼',
    receiverRegion: '北京市/北京市/朝阳区/建外街道'
  },
  {
    id: 'P2035091978689',
    orderTime: '2035-09-19 9:39:39',
    liveStream: '小红书订单',
    customerName: '周杰伦',
    orderStatus: 'shipped',
    afterSaleStatus: '无售后',
    receivableAmount: '¥23.80',
    selected: false,
    shippedCount: 1,
    totalCount: 1,
    isOverdue: false,
    items: [
      {
        image: '',
        name: '三十九度超鲜 国产贵妃芒',
        skuId: '2468896545',
        price: '¥23.80',
        quantity: 1,
        specs: '默认规格',
        discount: 0,
        shipping: 0
      }
    ],
    priceAndQuantity: '¥23.80 x 1',
    userNote: '',
    orderNote: '',
    receiverName: '周杰伦',
    receiverPhone: '13800138000',
    receiverAddress: '天朝北路1号楼',
    receiverRegion: '北京市/北京市/朝阳区/建外街道'
  },
  {
    id: 'P2035091978689',
    orderTime: '2035-09-19 9:39:39',
    liveStream: '蝉蜕号',
    customerName: '周杰伦',
    orderStatus: 'completed',
    afterSaleStatus: '无售后',
    receivableAmount: '¥56.90',
    selected: false,
    shippedCount: 1,
    totalCount: 1,
    isOverdue: false,
    items: [
      {
        image: '',
        name: '正大食品（CP）鸡翅中',
        skuId: '2468896545',
        price: '¥56.90',
        quantity: 1,
        specs: '默认规格',
        discount: 0,
        shipping: 0
      }
    ],
    priceAndQuantity: '¥56.90 x 1',
    userNote: '',
    orderNote: '',
    receiverName: '周杰伦',
    receiverPhone: '13800138000',
    receiverAddress: '天朝北路1号楼',
    receiverRegion: '北京市/北京市/朝阳区/建外街道'
  },
  {
    id: 'P2035091978689',
    orderTime: '2035-09-19 9:39:39',
    liveStream: '抖音直播',
    customerName: '周杰伦',
    orderStatus: 'closed',
    afterSaleStatus: '无售后',
    receivableAmount: '¥56.90',
    selected: false,
    shippedCount: 0,
    totalCount: 1,
    isOverdue: true,
    items: [
      {
        image: '',
        name: '飘柔洗护香波',
        skuId: '2468896545',
        price: '¥56.90',
        quantity: 1,
        specs: '默认规格',
        discount: 0,
        shipping: 0
      }
    ],
    priceAndQuantity: '¥56.90 x 1',
    userNote: '',
    orderNote: '',
    receiverName: '周杰伦',
    receiverPhone: '13800138000',
    receiverAddress: '天朝北路1号楼',
    receiverRegion: '北京市/北京市/朝阳区/建外街道'
  }
]);

// 全选/取消全选
const toggleSelectAll = (val: boolean) => {
  orderList.value.forEach(order => {
    order.selected = val;
  });
};

// 处理单个订单选中状态变化
const handleOrderSelection = () => {
  allSelected.value = orderList.value.every(order => order.selected);
};

// 分页相关
const total = ref(100);

const handleSizeChange = (size: number) => {
  searchForm.pageSize = size;
  fetchOrderList();
};

const handleCurrentChange = (page: number) => {
  searchForm.currentPage = page;
  fetchOrderList();
};

// 选中行
const selectedRows = ref<any[]>([]);
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 抽屉相关
const drawer = reactive({
  visible: false
});

const currentOrder = ref<any>(null);

// 查看订单详情
const viewOrderDetail = (row: any) => {
  // 創建一個深拷貝，避免引用同一個對象
  currentOrder.value = JSON.parse(JSON.stringify(row));
  drawer.visible = true;
};

// 页面加载时获取数据
fetchOrderList();

// 添加onMounted钩子确保页面载入时显示数据
onMounted(() => {
  // 確保顯示所有訂單
  fetchOrderList();
});

// 生成订单号
const generateOrderId = () => {
  // P + 订单生成日期 + 5位随机数字
  const date = dayjs().format('YYYYMMDD');
  const random = Math.floor(10000 + Math.random() * 90000); // 5位随机数
  
  return `P${date}${random}`;
};

// 判断订单超时状态
const checkOrderOverdue = (orderStatus: string | number, orderTime: string) => {
  if (orderStatus !== '2' && orderStatus !== 'paid') return false;
  
  const orderDate = dayjs(orderTime);
  const now = dayjs();
  const hoursDiff = now.diff(orderDate, 'hour');
  
  // 超过72小时未发货显示超时标签
  return hoursDiff >= 72;
};

// 处理取消订单
const handleCancelOrder = async (order: any) => {
  try {
    await cancelOrder(order.id, '用户取消');
    ElMessage.success('订单取消成功');
    fetchOrderList(); // 刷新列表
  } catch (error) {
    ElMessage.error('订单取消失败');
  }
};

// 处理改价
const handleChangePrice = async (order: any, newPrice: string) => {
  try {
    const amount = parseFloat(newPrice.replace('¥', ''));
    await changeOrderPrice(order.id, amount);
    ElMessage.success('订单改价成功');
    fetchOrderList(); // 刷新列表
  } catch (error) {
    ElMessage.error('订单改价失败');
  }
};

// 取消订单弹窗相关
const cancelDialog = reactive({
  visible: false,
  currentOrder: null as any,
  form: {
    reasons: [] as string[],
    remark: ''
  },
  rules: {
    reasons: [{ required: true, message: '请选择取消原因', trigger: 'change', type: 'array' }],
    remark: [{ max: 100, message: '备注长度不能超过100个字符', trigger: 'blur' }]
  }
});

const cancelFormRef = ref<any>(null);

// 打开取消订单弹窗
const openCancelDialog = (order: any) => {
  cancelDialog.currentOrder = order;
  cancelDialog.form.reasons = [];
  cancelDialog.form.remark = '';
  cancelDialog.visible = true;
};

// 提交取消订单
const submitCancelOrder = () => {
  if (!cancelFormRef.value) return;
  
  cancelFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const reasons = cancelDialog.form.reasons.join(',');
        await cancelOrder(cancelDialog.currentOrder.id, reasons);
        ElMessage.success('操作成功');
        cancelDialog.visible = false;
        // 更新订单状态为已关闭
        cancelDialog.currentOrder.orderStatus = OrderStatus.Closed;
        fetchOrderList();
      } catch (error) {
        ElMessage.error('取消订单失败');
      }
    }
  });
};

// 修改收货地址弹窗相关
const addressDialog = reactive({
  visible: false,
  currentOrder: null as any,
  form: {
    name: '',
    phone: '',
    region: [] as string[],
    address: ''
  },
  rules: {
    name: [
      { required: true, message: '请输入收货人姓名', trigger: 'blur' },
      { max: 30, message: '收货人姓名最多30个字符', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[0-9]{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    region: [{ required: true, message: '请选择省/市/区/街道', trigger: 'change' }],
    address: [
      { required: true, message: '请输入详细地址', trigger: 'blur' },
      { max: 30, message: '详细地址最多30个字符', trigger: 'blur' }
    ]
  },
  // 更完整的中国地区数据
  regionOptions: [
    {
      value: '110000',
      label: '北京市',
      children: [
        {
          value: '110100',
          label: '北京市',
          children: [
            {
              value: '110101',
              label: '东城区',
              children: [
                { value: '110101001', label: '东华门街道' },
                { value: '110101002', label: '景山街道' },
                { value: '110101003', label: '朝阳门街道' },
                { value: '110101004', label: '建国门街道' }
              ]
            },
            {
              value: '110102',
              label: '西城区',
              children: [
                { value: '110102001', label: '西长安街街道' },
                { value: '110102002', label: '新街口街道' },
                { value: '110102003', label: '月坛街道' },
                { value: '110102004', label: '展览路街道' }
              ]
            },
            {
              value: '110105',
              label: '朝阳区',
              children: [
                { value: '110105001', label: '建外街道' },
                { value: '110105002', label: '朝外街道' },
                { value: '110105003', label: '呼家楼街道' },
                { value: '110105004', label: '三里屯街道' }
              ]
            },
            {
              value: '110106',
              label: '丰台区',
              children: [
                { value: '110106001', label: '卢沟桥街道' },
                { value: '110106002', label: '丰台街道' },
                { value: '110106003', label: '新村街道' }
              ]
            }
          ]
        }
      ]
    },
    {
      value: '310000',
      label: '上海市',
      children: [
        {
          value: '310100',
          label: '上海市',
          children: [
            {
              value: '310101',
              label: '黄浦区',
              children: [
                { value: '310101001', label: '南京东路街道' },
                { value: '310101002', label: '外滩街道' },
                { value: '310101003', label: '半淞园路街道' }
              ]
            },
            {
              value: '310104',
              label: '徐汇区',
              children: [
                { value: '310104001', label: '湖南路街道' },
                { value: '310104002', label: '天平路街道' },
                { value: '310104003', label: '枫林路街道' }
              ]
            },
            {
              value: '310112',
              label: '闵行区',
              children: [
                { value: '310112001', label: '莘庄镇' },
                { value: '310112002', label: '七宝镇' },
                { value: '310112003', label: '浦江镇' }
              ]
            },
            {
              value: '310113',
              label: '宝山区',
              children: [
                { value: '310113001', label: '友谊路街道' },
                { value: '310113002', label: '吴淞街道' },
                { value: '310113003', label: '张庙街道' }
              ]
            },
            {
              value: '310115',
              label: '浦东新区',
              children: [
                { value: '310115001', label: '陆家嘴街道' },
                { value: '310115002', label: '花木街道' },
                { value: '310115003', label: '金杨新村街道' }
              ]
            }
          ]
        }
      ]
    },
    {
      value: '440000',
      label: '广东省',
      children: [
        {
          value: '440100',
          label: '广州市',
          children: [
            {
              value: '440103',
              label: '荔湾区',
              children: [
                { value: '440103001', label: '沙面街道' },
                { value: '440103002', label: '岭南街道' },
                { value: '440103003', label: '华林街道' }
              ]
            },
            {
              value: '440104',
              label: '越秀区',
              children: [
                { value: '440104001', label: '北京街道' },
                { value: '440104002', label: '六榕街道' },
                { value: '440104003', label: '流花街道' }
              ]
            },
            {
              value: '440105',
              label: '海珠区',
              children: [
                { value: '440105001', label: '赤岗街道' },
                { value: '440105002', label: '新港街道' },
                { value: '440105003', label: '江南大道街道' }
              ]
            },
            {
              value: '440106',
              label: '天河区',
              children: [
                { value: '440106001', label: '天河南街道' },
                { value: '440106002', label: '石牌街道' },
                { value: '440106003', label: '员村街道' }
              ]
            }
          ]
        },
        {
          value: '440300',
          label: '深圳市',
          children: [
            {
              value: '440303',
              label: '罗湖区',
              children: [
                { value: '440303001', label: '桂园街道' },
                { value: '440303002', label: '东门街道' },
                { value: '440303003', label: '南湖街道' }
              ]
            },
            {
              value: '440304',
              label: '福田区',
              children: [
                { value: '440304001', label: '福田街道' },
                { value: '440304002', label: '园岭街道' },
                { value: '440304003', label: '沙头街道' }
              ]
            },
            {
              value: '440305',
              label: '南山区',
              children: [
                { value: '440305001', label: '南头街道' },
                { value: '440305002', label: '蛇口街道' },
                { value: '440305003', label: '粤海街道' }
              ]
            }
          ]
        }
      ]
    },
    {
      value: '120000',
      label: '天津市',
      children: [
        {
          value: '120100',
          label: '天津市',
          children: [
            {
              value: '120101',
              label: '和平区',
              children: [
                { value: '120101001', label: '小白楼街道' },
                { value: '120101002', label: '新兴街道' },
                { value: '120101003', label: '南营门街道' }
              ]
            },
            {
              value: '120102',
              label: '河东区',
              children: [
                { value: '120102001', label: '大王庄街道' },
                { value: '120102002', label: '春华街道' },
                { value: '120102003', label: '唐家口街道' }
              ]
            }
          ]
        }
      ]
    },
    {
      value: '130000',
      label: '河北省',
      children: [
        {
          value: '130100',
          label: '石家庄市',
          children: [
            {
              value: '130102',
              label: '长安区',
              children: [
                { value: '130102001', label: '建北街道' },
                { value: '130102002', label: '广安街道' },
                { value: '130102003', label: '胜北街道' }
              ]
            }
          ]
        },
        {
          value: '130200',
          label: '唐山市',
          children: [
            {
              value: '130202',
              label: '路南区',
              children: [
                { value: '130202001', label: '学院南路街道' },
                { value: '130202002', label: '友谊街道' },
                { value: '130202003', label: '新华街道' }
              ]
            }
          ]
        }
      ]
    }
  ]
});

const addressFormRef = ref<any>(null);

// 打开修改地址弹窗
const openAddressDialog = (order: any) => {
  addressDialog.currentOrder = order;
  
  // 设置默认值
  addressDialog.form.name = order.receiverName || '';
  addressDialog.form.phone = order.receiverPhone || '';
  
  // 尝试从现有区域信息解析级联选择器的值
  try {
    if (order.receiverRegion) {
      const regionParts = order.receiverRegion.split('/');
      if (regionParts.length > 0) {
        // 这里可能需要根据实际情况进行调整，尝试找到匹配的值
        // 由于真实场景下我们没法确定区域代码，所以这里简单处理
        addressDialog.form.region = [];
      }
    }
  } catch (e) {
    console.error('解析收货地区信息失败', e);
    addressDialog.form.region = [];
  }
  
  addressDialog.form.address = order.receiverAddress || '';
  addressDialog.visible = true;
};

// 提交地址修改
const submitAddressChange = () => {
  if (!addressFormRef.value) return;
  
  addressFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 构建区域信息字符串
        const regionLabels = addressDialog.form.region.map((code: string) => {
          // 根据选中的代码找到对应的标签
          // 这里简化处理，实际应该递归查找
          let label = '';
          addressDialog.regionOptions.forEach((province) => {
            if (province.value === code) {
              label = province.label;
            } else if (province.children) {
              province.children.forEach((city) => {
                if (city.value === code) {
                  label = city.label;
                } else if (city.children) {
                  city.children.forEach((district) => {
                    if (district.value === code) {
                      label = district.label;
                    } else if (district.children) {
                      district.children.forEach((street) => {
                        if (street.value === code) {
                          label = street.label;
                        }
                      });
                    }
                  });
                }
              });
            }
          });
          return label;
        }).filter(label => label).join('/');
        
        // 调用修改地址API
        await updateOrderAddress(addressDialog.currentOrder.id, {
          receiverName: addressDialog.form.name,
          receiverPhone: addressDialog.form.phone,
          receiverRegion: regionLabels, // 使用标签而不是编码
          receiverAddress: addressDialog.form.address
        });
        
        ElMessage.success('操作成功');
        addressDialog.visible = false;
        
        // 更新订单列表中的地址信息
        const orderIndex = orderList.value.findIndex(o => o.id === addressDialog.currentOrder.id);
        if (orderIndex !== -1) {
          orderList.value[orderIndex].receiverName = addressDialog.form.name;
          orderList.value[orderIndex].receiverPhone = addressDialog.form.phone;
          orderList.value[orderIndex].receiverRegion = regionLabels;
          orderList.value[orderIndex].receiverAddress = addressDialog.form.address;
        }
        
        // 如果是详情抽屉的订单，也更新它
        if (currentOrder.value && currentOrder.value.id === addressDialog.currentOrder.id) {
          currentOrder.value.receiverName = addressDialog.form.name;
          currentOrder.value.receiverPhone = addressDialog.form.phone;
          currentOrder.value.receiverRegion = regionLabels;
          currentOrder.value.receiverAddress = addressDialog.form.address;
        }
      } catch (error) {
        console.error('修改地址失败', error);
        ElMessage.error('修改地址失败');
      }
    }
  });
};

// 删除订单
const handleDeleteOrder = async (order: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该订单吗？此操作不可恢复', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true
    });
    
    await deleteOrder(order.id);
    ElMessage.success('订单删除成功');
    fetchOrderList(); // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除订单失败');
    }
  }
};

// 打开发货对话框
const shipDialog = reactive({
  visible: false,
  currentOrder: {} as any,
  form: {
    trackingNumber: '',
    expressCompany: ''
  },
  rules: {
    trackingNumber: [
      { required: true, message: '请输入物流单号', trigger: 'blur' }
    ],
    expressCompany: [
      { required: true, message: '请选择物流公司', trigger: 'change' }
    ]
  }
});

const shipFormRef = ref();

// 打开发货对话框
const openShipDialog = (order: any) => {
  shipDialog.currentOrder = order;
  shipDialog.visible = true;
  shipDialog.form.trackingNumber = '';
  shipDialog.form.expressCompany = '';
};

// 提交发货
const submitShipOrder = () => {
  if (!shipFormRef.value) return;
  
  shipFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await shipOrder(
          shipDialog.currentOrder.id, 
          shipDialog.form.trackingNumber,
          shipDialog.form.expressCompany
        );
        
        ElMessage.success('发货操作成功');
        shipDialog.visible = false;
        
        // 更新订单状态
        const orderIndex = orderList.value.findIndex(o => o.id === shipDialog.currentOrder.id);
        if (orderIndex !== -1) {
          orderList.value[orderIndex].orderStatus = OrderStatus.Shipped;
          orderList.value[orderIndex].shippedCount = orderList.value[orderIndex].totalCount;
        }
        
        // 如果是详情抽屉的订单，也更新它
        if (currentOrder.value && currentOrder.value.id === shipDialog.currentOrder.id) {
          currentOrder.value.orderStatus = OrderStatus.Shipped;
          currentOrder.value.shippedCount = currentOrder.value.totalCount;
        }
      } catch (error) {
        console.error('发货失败', error);
        ElMessage.error('发货失败');
      }
    }
  });
};

// 初始化订单数据
const handleInitOrderData = async () => {
  try {
    await initOrderData();
    ElMessage.success('订单数据初始化成功');
    fetchOrderList();
  } catch (error) {
    console.error('订单数据初始化失败', error);
  }
};

// 创建订单弹窗相关
const createOrderDialog = reactive({
  visible: false,
  form: {
    customerName: '',
    phone: '',
    receiverName: '',
    receiverPhone: '',
    region: [],
    address: '',
    items: [
      {
        productName: '',
        price: 0,
        quantity: 1,
        specifications: '',
        productImg: '/public/OIP-C.webp'
      }
    ],
    remark: '',
    channel: '官网',
    status: OrderStatus.Pending
  },
  rules: {
    customerName: [
      { required: true, message: '请输入客户姓名', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^1[0-9]{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    receiverName: [
      { required: true, message: '请输入收货人姓名', trigger: 'blur' }
    ],
    receiverPhone: [
      { required: true, message: '请输入收货人电话', trigger: 'blur' },
      { pattern: /^1[0-9]{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    region: [
      { required: true, message: '请选择省/市/区/街道', trigger: 'change' }
    ],
    address: [
      { required: true, message: '请输入详细地址', trigger: 'blur' }
    ],
    items: [
      {
        productName: { required: true, message: '请输入商品名称', trigger: 'blur' },
        price: { required: true, message: '请输入单价', trigger: 'blur' },
        quantity: { required: true, message: '请输入数量', trigger: 'blur' },
        specifications: { required: true, message: '请输入规格', trigger: 'blur' }
      }
    ],
    remark: [
      { max: 100, message: '备注长度不能超过100个字符', trigger: 'blur' }
    ],
    channel: [
      { required: true, message: '请选择推广渠道', trigger: 'change' }
    ],
    status: [
      { required: true, message: '请选择订单状态', trigger: 'change' }
    ]
  }
});

const createOrderFormRef = ref<any>(null);

// 打开创建订单弹窗
const openCreateOrderDialog = () => {
  createOrderDialog.form.customerName = '';
  createOrderDialog.form.phone = '';
  createOrderDialog.form.receiverName = '';
  createOrderDialog.form.receiverPhone = '';
  createOrderDialog.form.region = [];
  createOrderDialog.form.address = '';
  createOrderDialog.form.items = [
    {
      productName: '',
      price: 0,
      quantity: 1,
      specifications: '',
      productImg: '/public/OIP-C.webp'
    }
  ];
  createOrderDialog.form.remark = '';
  createOrderDialog.form.channel = '官网';
  createOrderDialog.form.status = OrderStatus.Pending;
  createOrderDialog.visible = true;
};

// 提交创建订单
const submitCreateOrder = () => {
  if (!createOrderFormRef.value) return;
  
  createOrderFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        loading.value = true;
        
        // 获取区域文本
        let regionText = '';
        try {
          if (createOrderDialog.form.region && createOrderDialog.form.region.length > 0) {
            // 根据选择的区域ID获取对应的文本
            const regionLabels = getRegionLabels(createOrderDialog.form.region);
            regionText = regionLabels.join('/');
          }
        } catch (e) {
          console.error('解析区域信息失败', e);
        }
        
        // 计算订单总金额
        const totalAmount = createOrderDialog.form.items.reduce((total, item) => {
          return total + (item.price * item.quantity);
        }, 0);
        
        // 生成订单编号
        const orderNo = `P${dayjs().format('YYYYMMDDHHmmss')}${Math.floor(1000 + Math.random() * 9000)}`;
        
        // 计算商品总数量
        const totalCount = createOrderDialog.form.items.reduce((total, item) => {
          return total + item.quantity;
        }, 0);
        
        // 生成一个随机的 objectId (24位十六进制字符)
        const generateObjectId = () => {
          const chars = '0123456789abcdef';
          let result = '';
          for (let i = 0; i < 24; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
          }
          return result;
        };
        
        // 构建符合LeanCloud格式的订单数据
        const orderData = {
          objectId: generateObjectId(), // 添加随机生成的 objectId
          orderNo,
          totalAmount,
          payAmount: totalAmount,
          discountAmount: 0,
          status: parseInt(createOrderDialog.form.status, 10),
          payStatus: parseInt(createOrderDialog.form.status, 10) > 1 ? 1 : 0, // 状态大于1表示已付款
          payType: 1, // 默认微信支付
          shipStatus: 0, // 默认未发货
          receiverName: createOrderDialog.form.receiverName,
          receiverPhone: createOrderDialog.form.receiverPhone,
          receiverAddress: createOrderDialog.form.address,
          receiverRegion: regionText,
          remark: createOrderDialog.form.remark,
          sellerRemark: '',
          refundStatus: 0, // 默认无售后
          channel: createOrderDialog.form.channel,
          items: createOrderDialog.form.items.map(item => ({
            productName: item.productName,
            productImg: item.productImg,
            price: item.price,
            quantity: item.quantity,
            skuId: Math.floor(1000000000 + Math.random() * 9000000000).toString(), // 生成随机SKU ID
            specifications: item.specifications || '默认规格'
          })),
          totalCount,
          shippedCount: 0,
          // 添加客户信息
          customerName: createOrderDialog.form.customerName,
          phone: createOrderDialog.form.phone
        };
        
        try {
          // 调用创建订单API
          const result = await request({
            url: `${API.CLASSES}/Order`,
            method: 'post',
            data: orderData
          });
          
          if (result && result.data) {
            // 不管是否返回 objectId，都认为创建成功
            ElMessage.success('订单创建成功');
            createOrderDialog.visible = false;
            
            // 重新获取订单列表
            await fetchOrderList();
          } else {
            throw new Error('创建订单失败，服务器未响应');
          }
        } catch (apiError) {
          console.error('API调用失败', apiError);
          
          // 如果API调用失败，尝试使用批量创建API
          try {
            await batchCreateOrders([orderData]);
            ElMessage.success('订单创建成功（批量创建）');
            createOrderDialog.visible = false;
            await fetchOrderList();
          } catch (batchError) {
            console.error('批量创建订单失败', batchError);
            throw batchError;
          }
        }
      } catch (error) {
        console.error('创建订单失败', error);
        ElMessage.error('创建订单失败');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 根据区域ID获取区域文本
const getRegionLabels = (regionIds: string[]) => {
  const labels: string[] = [];
  
  let options = addressDialog.regionOptions;
  let currentOption;
  
  for (let i = 0; i < regionIds.length; i++) {
    currentOption = options.find(option => option.value === regionIds[i]);
    if (currentOption) {
      labels.push(currentOption.label);
      options = currentOption.children || [];
    }
  }
  
  return labels;
};

// 移除商品项
const removeProductItem = (index: number) => {
  createOrderDialog.form.items.splice(index, 1);
};

// 添加商品项
const addProductItem = () => {
  createOrderDialog.form.items.push({
    productName: '',
    price: 0,
    quantity: 1,
    specifications: '',
    productImg: '/public/OIP-C.webp'
  });
};

</script>

<style scoped>
.order-management {
  padding: 20px;
}

.search-panel {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.panel-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 500;
}

.filter-label {
  display: inline-block;
  width: 80px;
  text-align: right;
  margin-right: 10px;
}

.search-form {
  margin-top: 15px;
}

.time-filter, .status-filters {
  display: flex;
  align-items: center;
  margin-top: 15px;
}

.status-filters {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.search-actions {
  margin-top: 20px;
}

.time-buttons {
  display: flex;
  gap: 10px;
}

.w-full {
  width: 100%;
}

.mt-4 {
  margin-top: 1rem;
}

.mr-2 {
  margin-right: 0.5rem;
}

/* 表头样式 */
.table-header {
  display: flex;
  align-items: center;
  padding: 16px;
  background-color: #f5f7fa;
  border-top: 1px solid #ebeef5;
  border-left: 1px solid #ebeef5;
  border-right: 1px solid #ebeef5;
}

.header-item {
  font-weight: 500;
}

.flex-grow {
  flex-grow: 1;
}

.text-center {
  text-align: center;
}

/* 订单项样式 */
.order-item {
  background: #fff;
  border: 1px solid #ebeef5;
  margin-bottom: 10px;
}

.order-info-row {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  font-size: 12px;
  color: #606266;
}

.order-info-text {
  margin-left: 20px;
}

.order-content {
  display: flex;
  padding: 16px;
}

.product-column {
  display: flex;
  flex-direction: column;
}

.product-item {
  display: flex;
  margin-bottom: 10px;
}

.product-img {
  flex: 0 0 80px;
}

.product-info {
  margin-left: 10px;
  flex: 1;
}

.product-name {
  font-weight: 500;
  margin-bottom: 5px;
}

.product-sku {
  color: #909399;
  font-size: 12px;
}

.user-note {
  font-size: 12px;
  color: #606266;
  margin-top: 8px;
}

.user-remark {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #606266;
}

.user-remark .el-icon {
  margin-right: 5px;
  font-size: 14px;
  color: #409EFF;
}

.order-note-edit {
  display: flex;
  align-items: center;
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
}

.order-note-edit .el-icon {
  margin-right: 5px;
  font-size: 14px;
  color: #67C23A;
}

.price-edit {
  font-size: 12px;
  margin-top: 5px;
}

.operation-column {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.operation-link {
  font-size: 12px;
  margin-bottom: 8px;
}

/* 批量操作区域 */
.batch-operation {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #fff;
  border: 1px solid #ebeef5;
  margin-top: 16px;
}

.batch-operation-text {
  margin-left: 20px;
  margin-right: 10px;
}

.batch-btn {
  margin-right: 10px;
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 订单详情抽屉样式 */
.order-detail-drawer {
  padding: 0 20px;
}

.info-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.info-item {
  display: flex;
}

.info-label {
  color: #606266;
  width: 80px;
}

.amount-info {
  padding: 16px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.amount-item.total {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #dcdfe6;
  font-weight: bold;
}

.total-amount {
  color: #f56c6c;
  font-size: 18px;
}

.note-info {
  padding: 16px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.note-item {
  margin-bottom: 8px;
}

.action-section {
  display: flex;
  gap: 16px;
  margin-top: 24px;
  justify-content: flex-end;
}

.price-quantity-item {
  margin-bottom: 5px;
}

.price-quantity-item:not(:last-child) {
  padding-bottom: 5px;
  border-bottom: 1px dashed #ebeef5;
}

.ship-status {
  margin-top: 5px;
}

.mt-1 {
  margin-top: 4px;
}

.info-item.full-width {
  grid-column: span 2;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.empty-data {
  background-color: #fff;
  padding: 40px 0;
  text-align: center;
  border: 1px solid #ebeef5;
  border-top: none;
}

.search-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.empty-state {
  padding: 40px 0;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-top: none;
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-section-title {
  font-weight: bold;
  margin: 15px 0 10px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.product-form-item {
  margin-bottom: 15px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.product-form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-weight: bold;
}

.add-product-btn {
  display: flex;
  justify-content: center;
  margin: 15px 0;
}
</style>